const baseUrl = ''
function reject(err) {
  const deferred = $.Deferred()
  deferred.reject(err)
  return deferred.promise()
}

function headers() {
  return {
    token: $.cookie('token')
  }
}

function ajax(type, mark, data) {
  return $.ajax({
    type: type,
    url: baseUrl + mark,
    // url: baseUrl + mark,
    dataType: 'json',
    headers: headers(),
    crossDomain: true,
    contentType: 'application/json; charset=utf-8',
    error() {
      layer.msg('网络错误')
    }
  }).then(res => {
    const code = res.code
    if (code >= 200 && code < 300) {
      return res.data
    } else {
      layer.msg(res.message, { icon: 2 })
      return reject(res)
    }
  })
}

export function get(mark, data) {
  return ajax('get', mark, data)
}
export function post(mark, data) {
  return ajax('post', mark, data)
}

export function upload(mark, data) {
  return $.ajax({
    type: 'post',
    url: baseUrl + mark,
    data: data,
    // 告诉jQuery不要去处理发送的数据
    processData: false,
    // 告诉jQuery不要去设置Content-Type请求头
    contentType: false,
    dataType: 'json',
    headers: headers(),
    error() {
      layer.msg('网络错误')
    }
  }).then(res => {
    const code = res.code
    if (code >= 200 && code < 300) {
      return res.data
    } else {
      layer.msg(res.message, { icon: 2 })
      return reject(res)
    }
  })
}

// 序列化表单
$.fn.serializeObject = function () {
  const o = {}
  const a = this.serializeArray()
  $.each(a, function () {
    if (o[this.name]) {
      if (!o[this.name].push) {
        o[this.name] = [o[this.name]]
      }
      o[this.name].push(this.value || '')
    } else {
      o[this.name] = this.value || ''
    }
  })
  return o
}

// 获取url参数
export function getQueryString(name) {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  const r = window.location.search.substr(1).match(reg)
  if (r != null) {
    return decodeURIComponent(r[2])
  }
  return null
}
